const app = getApp();
Page({
  data: {
    isLoggedIn: false,  // 登录状态
    pickupLocation: null,
    deliveryLocation: null,
    latitude: 0,
    longitude: 0,
    polyline: [],
    markers: [],
    pickup: {},
    delivery: {},
    orderStatus: '',
    currentTab: 0,
    steps: [
      { label: '派', time: '派单中', done: true },
      { label: '接', time: '待接单', done: false },
      { label: '取', time: '待取货', done: false },
      { label: '达', time: '待送达', done: false }
    ],
    goodsList: [],
    isRejected: false,
    orderSn: null,
  },

  onLoad(options) {

    // 检查登录状态
    this.checkLoginStatus();

    if (!this.data.isLoggedIn) {
      return; // 未登录时不处理订单数据
    }

    // 如果有直接传递的参数，也处理一下
    if (options.orderStatus) {
      this.setData({
        orderStatus: options.orderStatus,
        currentTab: options.orderStatus === '待接单' ? 0 : 1
      });
    }
  },

  onShow() {
    // 检查登录状态
    this.checkLoginStatus();

    if (!this.data.isLoggedIn) {
      return; // 未登录时不处理订单数据
    }

    try {
      const pickupStr = wx.getStorageSync('pickup');
      const deliveryStr = wx.getStorageSync('delivery');
      const orderStatus = wx.getStorageSync('orderStatus');
      const orderSn = wx.getStorageSync('orderSn');
      const userId = wx.getStorageSync('userId');
      const goodsStr = wx.getStorageSync('goods');

      const pickup = pickupStr ? JSON.parse(decodeURIComponent(pickupStr)) : null;
      const delivery = deliveryStr ? JSON.parse(decodeURIComponent(deliveryStr)) : null;
      const goodsList = goodsStr ? JSON.parse(decodeURIComponent(goodsStr)) : [];

      if (!pickup || !delivery) {
        return;
      }

      let currentTab = 0;
      if (orderStatus === '待接单') currentTab = 0;
      else if (orderStatus === '待取货' || orderStatus === '待拿货') currentTab = 1;
      else if (orderStatus === '待送达' || orderStatus === '待收货') currentTab = 2;
      else if (orderStatus === '已送达') currentTab = 3;

      // 如果没有匹配的状态，默认设置为待接单状态
      if (!orderStatus || (currentTab === 0 && orderStatus !== '待接单')) {
        currentTab = 0;
      }

      const steps = [
        { label: '派', time: '派单中', done: true },
        { label: '接', time: '待接单', done: currentTab >= 1 },
        { label: '取', time: '待取货', done: currentTab >= 2 },
        { label: '达', time: '待送达', done: currentTab >= 3 }
      ];

      this.setData({
        pickup,
        delivery,
        orderStatus,
        currentTab,
        steps,
        pickupLocation: { latitude: pickup.latitude, longitude: pickup.longitude },
        deliveryLocation: { latitude: delivery.latitude, longitude: delivery.longitude },
        goodsList,
        isRejected: false,
        orderSn,
        userId,
      }, () => {
        if (orderStatus === '待拿货') {
          this.acceptOrder(); // 会调用 updateOrderStatus 和 drawFirstRoute
        } else if (orderStatus === '待收货') {
          this.pickupOrder(); // 会调用 updateOrderStatus 和路线绘制
        } else {
          this.drawRoute(); // 默认绘制完整路径
        }
      });

      wx.removeStorageSync('pickup');
      wx.removeStorageSync('delivery');
      wx.removeStorageSync('orderStatus');
      wx.removeStorageSync('orderSn');
      wx.removeStorageSync('goods');
    } catch (err) {
      // 参数解析失败，静默处理
    }
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = app.globalData.ridertoken;
    const riderId = app.globalData.riderId;

    const isLoggedIn = !!(token && riderId);
    this.setData({ isLoggedIn });

    if (!isLoggedIn) {
      // 未登录时清空订单相关数据
      this.setData({
        pickupLocation: null,
        deliveryLocation: null,
        latitude: 0,
        longitude: 0,
        polyline: [],
        markers: [],
        pickup: {},
        delivery: {},
        orderStatus: '',
        currentTab: 0,
        goodsList: [],
        orderSn: null
      });
    }
  },

  // 跳转到登录页面
  goToLogin() {
    wx.navigateTo({
      url: '/pages/logs/logs'
    });
  },

  drawRoute() {
    const _this = this;
    const pickup = this.data.pickupLocation;
    const delivery = this.data.deliveryLocation;
    const key = app.globalData.locationKey;

    if (!pickup || !delivery) {
      wx.showToast({ title: '取餐或送达地址无效', icon: 'none' });
      return;
    }

    wx.request({
      url: 'https://apis.map.qq.com/ws/location/v1/ip',
      data: { key },
      success(res) {
        if (res.data.status !== 0) {
          wx.showToast({ title: 'IP定位失败', icon: 'none' });
          return;
        }

        const loc = res.data.result.location;
        const userLocation = {
          latitude: loc.lat,
          longitude: loc.lng
        };

        const from1 = `${userLocation.latitude},${userLocation.longitude}`;
        const to1 = `${pickup.latitude},${pickup.longitude}`;

        wx.request({
          url: `https://apis.map.qq.com/ws/direction/v1/driving/?from=${from1}&to=${to1}&key=${key}`,
          success(res1) {
            if (res1.data.status !== 0) {
              wx.showToast({ title: '路线1规划失败', icon: 'none' });
              return;
            }

            const coors1 = res1.data.result.routes[0].polyline;
            const pl1 = [];
            const kr = 1000000;
            for (let i = 2; i < coors1.length; i++) {
              coors1[i] = Number(coors1[i - 2]) + Number(coors1[i]) / kr;
            }
            for (let i = 0; i < coors1.length; i += 2) {
              pl1.push({ latitude: coors1[i], longitude: coors1[i + 1] });
            }

            const from2 = `${pickup.latitude},${pickup.longitude}`;
            const to2 = `${delivery.latitude},${delivery.longitude}`;

            wx.request({
              url: `https://apis.map.qq.com/ws/direction/v1/driving/?from=${from2}&to=${to2}&key=${key}`,
              success(res2) {
                if (res2.data.status !== 0) {
                  wx.showToast({ title: '路线2规划失败', icon: 'none' });
                  return;
                }

                const coors2 = res2.data.result.routes[0].polyline;
                const pl2 = [];
                for (let i = 2; i < coors2.length; i++) {
                  coors2[i] = Number(coors2[i - 2]) + Number(coors2[i]) / kr;
                }
                for (let i = 0; i < coors2.length; i += 2) {
                  pl2.push({ latitude: coors2[i], longitude: coors2[i + 1] });
                }

                const fullRoute = [...pl1, ...pl2];

                _this.setData({
                  latitude: userLocation.latitude,
                  longitude: userLocation.longitude,
                  polyline: [{
                    points: fullRoute,
                    color: '#58c16c',
                    width: 2,
                    borderColor: '#2f693c',
                    borderWidth: 1
                  }],
                  markers: [
                    {
                      id: 0,
                      latitude: userLocation.latitude,
                      longitude: userLocation.longitude,
                      width: 30,
                      height: 30,
                      label: { content: '我', color: '#333', fontSize: 12, bgColor: '#FFE736', borderRadius: 15, padding: 5 }
                    },
                    {
                      id: 1,
                      latitude: pickup.latitude,
                      longitude: pickup.longitude,
                      width: 30,
                      height: 30,
                      label: { content: '店家', color: '#fff', fontSize: 10, bgColor: '#FF6B35', borderRadius: 15, padding: 5 }
                    },
                    {
                      id: 2,
                      latitude: delivery.latitude,
                      longitude: delivery.longitude,
                      width: 30,
                      height: 30,
                      label: { content: '送达', color: '#fff', fontSize: 10, bgColor: '#1890FF', borderRadius: 15, padding: 5 }
                    }
                  ],
                  includePoints: [
                    { latitude: userLocation.latitude, longitude: userLocation.longitude },
                    pickup,
                    delivery
                  ]
                });
              }
            });
          }
        });
      }
    });
  },

  acceptOrder() {
    this.updateOrderStatus('待取货', 1);
    this.drawFirstRoute();  // 接单时只显示第一条路径
  },

  drawFirstRoute() {
    const _this = this;
    const pickup = this.data.pickupLocation;
    const key = app.globalData.locationKey;
  
    if (!pickup) {
      wx.showToast({ title: '取货地址无效', icon: 'none' });
      return;
    }
  
    // 先用IP定位获取用户当前位置
    wx.request({
      url: 'https://apis.map.qq.com/ws/location/v1/ip',
      data: { key },
      success(res) {
        if (res.data.status !== 0) {
          wx.showToast({ title: 'IP定位失败', icon: 'none' });
          return;
        }
  
        const userLocation = {
          latitude: res.data.result.location.lat,
          longitude: res.data.result.location.lng
        };
  
        const from = `${userLocation.latitude},${userLocation.longitude}`;
        const to = `${pickup.latitude},${pickup.longitude}`;
  
        wx.request({
          url: `https://apis.map.qq.com/ws/direction/v1/driving/?from=${from}&to=${to}&key=${key}`,
          success(res1) {
            if (res1.data.status !== 0) {
              wx.showToast({ title: '路线规划失败', icon: 'none' });
              return;
            }
  
            const coors = res1.data.result.routes[0].polyline;
            const pl = [];
            const kr = 1000000;
            for (let i = 2; i < coors.length; i++) {
              coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
            }
            for (let i = 0; i < coors.length; i += 2) {
              pl.push({ latitude: coors[i], longitude: coors[i + 1] });
            }
  
            _this.setData({
              latitude: userLocation.latitude,
              longitude: userLocation.longitude,
              polyline: [{
                points: pl,
                color: '#58c16c',
                width: 4
              }],
              markers: [
                {
                  id: 0,
                  latitude: userLocation.latitude,
                  longitude: userLocation.longitude,
                  width: 30,
                  height: 30,
                  label: { content: '我', color: '#333', fontSize: 12, bgColor: '#FFE736', borderRadius: 15, padding: 5 }
                },
                {
                  id: 1,
                  latitude: pickup.latitude,
                  longitude: pickup.longitude,
                  width: 30,
                  height: 30,
                  label: { content: '店家', color: '#fff', fontSize: 10, bgColor: '#FF6B35', borderRadius: 15, padding: 5 }
                }
              ],
              includePoints: [
                { latitude: userLocation.latitude, longitude: userLocation.longitude },
                pickup
              ]
            });
          }
        });
      }
    });
  },

  assignRider() {
    const token = app.globalData.ridertoken;
    const ip = app.globalData.userIPInfo;
    let riderId = app.globalData.riderId;

    // 如果 globalData 中没有 riderId，尝试从本地存储获取
    if (!riderId) {
      riderId = wx.getStorageSync('riderId');
      if (riderId) {
        app.globalData.riderId = riderId; // 更新到 globalData
      }
    }

    // 检查必要参数
    if (!token) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }

    if (!riderId) {
      wx.showToast({ title: '骑手信息获取失败，请重新登录', icon: 'none' });
      return;
    }

    if (!this.data.orderSn) {
      wx.showToast({ title: '订单信息无效', icon: 'none' });
      return;
    }

    wx.request({
      url: `${ip}/api/orders/assign-rider`,
      method: 'POST',
      header: {
        'Authorization': 'Bearer ' + token,
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: {
        orderSn: this.data.orderSn,
        riderId: riderId
      },
      success: res => {
        if (res.data.code === 200) {
          wx.showToast({ title: '接单成功', icon: 'success' });
          this.updateOrderStatus('待取货', 1);
          this.drawFirstRoute();  // 接单时只显示第一条路径
        } else {
          wx.showToast({ title: res.data.msg || res.data.message || '接单失败', icon: 'none' });
        }
      },
      fail: (err) => {
        wx.showToast({ title: '网络请求失败', icon: 'none' });
      }
    });
  },

  pickupOrder() {
    this.updateOrderStatus('待送达', 2);
    this.drawSecondRoute(); // ✅ 绘制第二段路线
    setTimeout(() => {
      this.drawRouteFromCurrentToDelivery();
    }, 2000);
  },

  fetchGoodsInfo() {
    const ip = app.globalData.userIPInfo;
    const token = app.globalData.ridertoken;
    const orderSn = this.data.orderSn;
  
    wx.request({
      url: `${ip}/api/orders/get-goods`,
      method: 'POST',
      header: {
        'Authorization': 'Bearer ' + token,
        'Content-Type': 'application/x-www-form-urlencoded'  // 必须加这个
      },
      data: {
        orderSn
      },
      success: res => {
        if (res.data.code === 200) {
          wx.showToast({
            title: res.data.message || '拿货确认成功',
            icon: 'success'
          });
          this.updateOrderStatus('待送达', 2);
          this.drawSecondRoute(); // ✅ 绘制第二段路线
          setTimeout(() => {
            this.drawRouteFromCurrentToDelivery();
          }, 2000);
        } else {
          wx.showToast({
            title: res.data.message || '拿货确认失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '请求失败，请重试',
          icon: 'none'
        });
      }
    });
  },  

  drawRouteFromCurrentToDelivery() {
    const _this = this;
    const delivery = this.data.deliveryLocation;
    const key = app.globalData.locationKey;
  
    if (!delivery) {
      wx.showToast({ title: '送达地址无效', icon: 'none' });
      return;
    }
  
    // 改用 IP 定位
    wx.request({
      url: 'https://apis.map.qq.com/ws/location/v1/ip',
      data: { key },
      success(res) {
        if (res.data.status !== 0) {
          wx.showToast({ title: 'IP定位失败', icon: 'none' });
          return;
        }
  
        const userLat = res.data.result.location.lat;
        const userLng = res.data.result.location.lng;
  
        const from = `${userLat},${userLng}`;
        const to = `${delivery.latitude},${delivery.longitude}`;
  
        wx.request({
          url: `https://apis.map.qq.com/ws/direction/v1/driving/?from=${from}&to=${to}&key=${key}`,
          success(res1) {
            if (res1.data.status !== 0) {
              wx.showToast({ title: '路线规划失败', icon: 'none' });
              return;
            }
  
            const coors = res1.data.result.routes[0].polyline;
            const pl = [];
            const kr = 1000000;
            for (let i = 2; i < coors.length; i++) {
              coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
            }
            for (let i = 0; i < coors.length; i += 2) {
              pl.push({ latitude: coors[i], longitude: coors[i + 1] });
            }
  
            _this.setData({
              latitude: userLat,
              longitude: userLng,
              polyline: [{
                points: pl,
                color: '#2E8B57',
                width: 4
              }],
              markers: [
                {
                  id: 0,
                  latitude: userLat,
                  longitude: userLng,
                  width: 30,
                  height: 30,
                  label: { content: '我', color: '#333', fontSize: 12, bgColor: '#FFE736', borderRadius: 15, padding: 5 }
                },
                {
                  id: 2,
                  latitude: delivery.latitude,
                  longitude: delivery.longitude,
                  width: 30,
                  height: 30,
                  label: { content: '送达', color: '#fff', fontSize: 10, bgColor: '#1890FF', borderRadius: 15, padding: 5 }
                }
              ],
              includePoints: [
                { latitude: userLat, longitude: userLng },
                delivery
              ]
            });
          }
        });
      },
      fail() {
        wx.showToast({ title: 'IP定位请求失败', icon: 'none' });
      }
    });
  },  

  drawSecondRoute() {
    const pickup = this.data.pickupLocation;
    const delivery = this.data.deliveryLocation;
    const key = app.globalData.locationKey;
    const _this = this;
  
    wx.request({
      url: `https://apis.map.qq.com/ws/direction/v1/driving/?from=${pickup.latitude},${pickup.longitude}&to=${delivery.latitude},${delivery.longitude}&key=${key}`,
      success(res) {
        if (res.data.status !== 0) {
          wx.showToast({ title: '路线规划失败', icon: 'none' });
          return;
        }
  
        const coors = res.data.result.routes[0].polyline;
        const pl = [];
        const kr = 1000000;
        for (let i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
        }
        for (let i = 0; i < coors.length; i += 2) {
          pl.push({ latitude: coors[i], longitude: coors[i + 1] });
        }
  
        _this.setData({
          polyline: [{
            points: pl,
            color: '#2E8B57',
            width: 2
          }],
          markers: [
            {
              id: 1,
              latitude: pickup.latitude,
              longitude: pickup.longitude,
              width: 30,
              height: 30,
              label: { content: '我', color: '#333', fontSize: 12, bgColor: '#FFE736', borderRadius: 15, padding: 5 }
            },
            {
              id: 2,
              latitude: delivery.latitude,
              longitude: delivery.longitude,
              width: 30,
              height: 30,
              label: { content: '送达', color: '#fff', fontSize: 10, bgColor: '#1890FF', borderRadius: 15, padding: 5 }
            }
          ],
          includePoints: pl  // 这里改成整个路线点数组
        });        
      }
    });
  },

  deliverOrder() {
    this.updateOrderStatus('已送达', 3);
  },

  fetchGoodsOrder() {
    const ip = app.globalData.userIPInfo;
    const token = app.globalData.ridertoken;
    const userId = this.data.userId;      // 假设你有保存用户ID
    const orderSn = this.data.orderSn;
  
    wx.request({
      url: ''+ip+'/api/orders/complete',
      method: 'POST',
      header: {
        'Authorization': 'Bearer ' + token,
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: {
        userId,
        orderSn
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({ title: '订单已完成', icon: 'success' });
          this.updateOrderStatus('已送达', 3);
        } else {
          wx.showToast({ title: res.data.message || '完成订单失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '请求失败，请重试', icon: 'none' });
      }
    });
  }, 

  rejectOrder() {
    let steps = this.data.steps;
    for (let i = 1; i < steps.length; i++) {
      steps[i].done = i < 3;
    }
    this.setData({
      isRejected: true,
      orderStatus: '拒收',
      currentTab: 3,
      steps
    });
  },

  updateOrderStatus(status, tabIndex) {
    let steps = this.data.steps;
    for (let i = 1; i < steps.length; i++) {
      steps[i].done = i <= tabIndex;
    }
    this.setData({
      orderStatus: status,
      currentTab: tabIndex,
      steps,
      isRejected: false
    });
  },

  callPickup() {
    wx.makePhoneCall({ phoneNumber: this.data.pickup.phone });
  },

  callDelivery() {
    wx.makePhoneCall({ phoneNumber: this.data.delivery.phone });
  }
});
